package cn.tedu.fresheveryday.controller;

import cn.tedu.fresheveryday.exception.ServiceException;
import cn.tedu.fresheveryday.restful.JsonResult;
import cn.tedu.fresheveryday.restful.ResponseCode;
import cn.tedu.fresheveryday.service.ICommentImageService;
import cn.tedu.fresheveryday.util.StringUtils;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@RestController
@Api(tags = "评论图片模块")
@RequestMapping(path = "/comment_image", produces = "application/json;charset=utf-8")
public class CommentImageController {
    @Value("${uploads.path}")
    private String path;

    @Autowired
    ICommentImageService service;

    /**
     * 上传图片
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public JsonResult upload(MultipartFile file) {
        String directory = "/comment/";
        String fileName = directory + StringUtils.getFileName(file);
        File targetFile = new File(path + fileName);

        try {
            file.transferTo(targetFile);

            return JsonResult.success(null, fileName);
        } catch (IOException e) {
            e.printStackTrace();

            return JsonResult.error(new ServiceException(ResponseCode.BAD_REQUEST, "系统繁忙，请稍后重试..."));
        }
    }

}